package com.artron.mediaartron.ui.fragment.made.edit;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.artron.baselib.base.BaseStaticFragment;
import com.artron.baselib.image.ImageUtils;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.entity.FrameData;
import com.artron.mediaartron.data.entity.ImageData;
import com.artron.mediaartron.data.entity.Works;
import com.artron.mediaartron.data.production.FrameConstant;
import com.artron.mediaartron.data.production.SuitableSizeHelper;
import com.artron.mediaartron.ui.activity.CustomSelectionActivity;
import com.artron.mediaartron.ui.activity.EditPageActivity;
import com.artron.mediaartron.ui.activity.PictureSelectionActivity;
import com.artron.mediaartron.ui.widget.TransformCustomImageView;
import com.bilibili.boxing.Boxing;
import com.bilibili.boxing.model.config.BoxingConfig;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import butterknife.BindView;

import static com.artron.mediaartron.ui.activity.PictureSelectionActivity.IS_HAVE_TAB_FRAGMENT;


/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-09-28.
 */

public class EditPageFragment extends BaseStaticFragment implements View.OnClickListener {

    public static final int REQUEST_CODE = 1000;

    @BindView(R.id.EditPageFragment_iv_edit)
    protected TransformCustomImageView mIvEdit;
    @BindView(R.id.EditPageFragment_fl_parent)
    protected FrameLayout mFlParent;
    @BindView(R.id.EditPageFragment_tv_recovery)
    protected TextView mTvRecovery;
    @BindView(R.id.EditPageFragment_tv_selection)
    protected TextView mTvSelection;
    @BindView(R.id.EditPageFragment_tv_tips)
    protected TextView mTvTips;
    private FrameData mData;
    private SuitableSizeHelper mHelper;
    private String mPath;

    public static EditPageFragment newInstance(FrameData data) {
        EditPageFragment fragment = new EditPageFragment();
        fragment.init(data);
        return fragment;
    }

    private void init(FrameData data) {
        this.mData = data;
        mHelper = SuitableSizeHelper.getHelper();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_edit_page;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    protected void initView() {
        Matrix matrix = mHelper.getMatrix();
        if (matrix != null) {
            float scaleFactor = mHelper.getScaleFactor();
            mIvEdit.setMatrix(matrix);
            mIvEdit.setScaleFactor(scaleFactor);
        }

        mFlParent.post(new Runnable() {
            @Override
            public void run() {
                float ivHeight = mFlParent.getHeight();
                float ivWidth = mFlParent.getWidth();
//
                final ImageData image = mData.getImage();
                int type = mData.getType();
                if (type == CustomSelectionActivity.CUSTOM_MADE) {
                    image.setHeight(mData.getHeight() - FrameConstant.BLANK_CUSTOM_MADE);
                    image.setWidth(mData.getWidth() - FrameConstant.BLANK_CUSTOM_MADE);
                } else {
                    image.setHeight(mData.getHeight());
                    image.setWidth(mData.getWidth());
                }

                ViewGroup.LayoutParams params = mIvEdit.getLayoutParams();
                if (image.getWidth() >= image.getHeight()) {
                    params.height = (int) (ivWidth / image.getWidth() * image.getHeight() + .5f);
                    params.width = (int) ivWidth;
                } else {
                    params.width = (int) (ivHeight / image.getHeight() * image.getWidth() + .5f);
                    params.height = (int) ivHeight;
                    if (params.width > ivWidth) {
                        params.width = (int) ivWidth;
                        params.height = (int) (ivWidth / image.getWidth() * image.getHeight() + .5f);
                    }
                }

                mIvEdit.setLayoutParams(params);

                Glide.with(mContext)
                        .load(image.getContentImage())
                        .skipMemoryCache(true)
                        .into(new SimpleTarget<GlideDrawable>() {
                            @Override
                            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                                mIvEdit.setImageDrawable(resource);
                            }
                        });
            }
        });


        mTvSelection.setOnClickListener(this);
        mTvRecovery.setOnClickListener(this);

        mIvEdit.setOnScaleChangeListener(new TransformCustomImageView.OnScaleChangeListener() {
            @Override
            public void onScale(TransformCustomImageView iv, float scaleFactor) {
                float degree = mHelper.getSuitableDegree(iv.getCurrentRotateDegree());
                float[] imageSize = mHelper.getImageSize(iv, degree);
                ImageData image = mData.getImage();
                boolean flag = mHelper.isSuitableSize(image.getWidth(), image.getHeight()
                            , imageSize[2] , imageSize[3]);
                if (!flag) {
                    mTvTips.setVisibility(View.VISIBLE);
                } else {
                    mTvTips.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.EditPageFragment_tv_recovery:
                mIvEdit.recovery();
                break;
            case R.id.EditPageFragment_tv_selection:
                BoxingConfig config = new BoxingConfig(BoxingConfig.Mode.SINGLE_IMG)
                        .needCamera(R.drawable.ic_selection_picture_camera)
                        .withMaxCount(10);
                Boxing boxing = Boxing.of(config).withIntent(mContext, PictureSelectionActivity.class);
                Intent intent = boxing.getIntent();
                intent.putExtra(IS_HAVE_TAB_FRAGMENT, true);
                boxing.start((Activity) mContext, REQUEST_CODE);
                break;
        }
    }

    public void updateImagePath(String path) {
        mPath = path;
        mIvEdit.setReFix(false);
        Glide.with(mContext)
                .load(path)
                .skipMemoryCache(true)
                .into(new SimpleTarget<GlideDrawable>() {
                    @Override
                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                        mIvEdit.setImageDrawable(resource);
                    }
                });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_save:
                float degree = mHelper.getSuitableDegree(mIvEdit.getCurrentRotateDegree());
                float[] imageSize = mHelper.getImageSize(mIvEdit, degree);

                Bitmap bitmap = ((GlideBitmapDrawable) mIvEdit.getDrawable()).getBitmap();
                Matrix rotateMatrix = new Matrix();
                rotateMatrix.setRotate(degree, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
                Bitmap rotateBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), rotateMatrix, true);
                Bitmap result = Bitmap.createBitmap(rotateBitmap, ((int) imageSize[0]),
                        ((int) imageSize[1]), ((int) imageSize[2]), ((int) imageSize[3]));
                rotateBitmap.recycle();
                System.runFinalization();
                System.gc();

                mHelper.setClipBitmap(result);
                mHelper.setMatrix(mIvEdit.getEditImageMatrix());
                mHelper.setScaleFactor(mIvEdit.getScaleFactor());

                Works works = new Works();
                works.addEditBean(new Works.MaterialEditBean("", 1, 1, imageSize[0], imageSize[1],
                        imageSize[2], imageSize[3], degree, 1, 1, 1));
                mHelper.setWorks(works);
                if (!TextUtils.isEmpty(mPath)) {
                    mData.getImage().setContentImage(mPath);
                }

                ((EditPageActivity) getActivity()).onBackPressWithImage();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}
